package com.zjpavt.client.page;

import com.zjpavt.client.Connection;
import com.zjpavt.client.hal.LedScreen;
import com.zjpavt.client.hal.LoopManager;
import com.zjpavt.client.hal.network.NetworkManager;
import com.zjpavt.client.page.pageunit.ScreenLine;
import com.zjpavt.client.page.abstractpage.AbstractEditablePage;
import com.zjpavt.client.page.editableunit.EditUnitNum;
import com.zjpavt.client.util.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 第一页 时间设置页面
 * @author zyc
 */
@Slf4j
public class TimePage extends AbstractEditablePage {

    private static final Logger logger = LoggerFactory.getLogger(TimePage.class);

    private SimpleDateFormat dateFormat = new SimpleDateFormat(Consts.DATE_FORMAT);
    private SimpleDateFormat timeFormat = new SimpleDateFormat(Consts.TIME_FORMAT);

    public TimePage(int pageNum, long mRefreshPeriod) {
        super(pageNum, mRefreshPeriod);
    }

    @Override
    public void refreshPage() {
        LedScreen.getInstance().setText(generatePageContent(new Date()));
    }

    public List<ScreenLine> generatePageContent(Date date) {
//	    fixme
        if (Calendar.getInstance().get(Calendar.YEAR) < 2019) {
            log.error("get time early than 2019, now date is " + new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, 2019);
            try {
                date = calendar.getTime();
                CmdUtil.setDate(calendar.getTime());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        List<ScreenLine> lists = new ArrayList<>();
        lists.add(new ScreenLine.ScreenLineBuilder()
                  .text("TIME" + timeFormat.format(date))
                  .pageNum(getPageNum())
                  .build());
        lists.add(new ScreenLine.ScreenLineBuilder()
                  .text("week:" + (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1))
                  .build());
        lists.add(new ScreenLine.ScreenLineBuilder()
                  .text(dateFormat.format(date))
                  .build());
        lists.add(new ScreenLine.ScreenLineBuilder()
                  .text(String.format("%05d", (int)LoopManager.getInstance().getManualModalRemainTime()))
                  .alignRight()
                  .build());
        return lists;
    }

    /*	@Override
    	protected Runnable getRefreshTask() {
    		//此处按块刷新，给每个可编辑块按照当前时间赋值，只有值变化时才刷新当前内容
    		return this::setDefaultVal;
    	}*/

    @Override
    public void initEditUnits() {
        addEditUnit(new EditUnitNum(1, 5, 6, 0, 23, 1));//HOUR
        addEditUnit(new EditUnitNum(1, 8, 9, 0, 59, 1));//MINUTE
        addEditUnit(new EditUnitNum(1, 11, 12, 0, 59, 1));//SECOND
        addEditUnit(new EditUnitNum(3, 1, 4, 1997, 2999, 1));    //YEAR
        addEditUnit(new EditUnitNum(3, 6, 7, 1, 12, 1));    //MONTH
        addEditUnit(new EditUnitNum(3, 9, 10, 1, 31, 1));    //DAY
        addEditUnit(new EditUnitNum(4, 11, 15, 60 * 60, 3 * 60 * 60, 3600));    //DAY
    }


    @Override
    public void onKeyDown() {
        if (isInEditMode()) {
            getEditUnit(getCurrBlinkIndex()).onDown();
        } else {
            super.onKeyDown();
        }
    }

    @Override
    public void onKeyUp() {
        if (isInEditMode()) {
            getEditUnit(getCurrBlinkIndex()).onUp();
        } else {
            super.onKeyUp();
        }
    }

    /**
     * 根据当前状态设置unit初始值
     */
    @Override
    public void setDefaultVal() {
        Calendar calendar = Calendar.getInstance();
        getEditUnit(2).setCurrentVal(calendar.get(Calendar.SECOND));
        getEditUnit(1).setCurrentVal(calendar.get(Calendar.MINUTE));
        getEditUnit(0).setCurrentVal(calendar.get(Calendar.HOUR_OF_DAY));
        getEditUnit(3).setCurrentVal(calendar.get(Calendar.YEAR));
        getEditUnit(4).setCurrentVal(calendar.get(Calendar.MONTH) + 1);
        getEditUnit(5).setCurrentVal(calendar.get(Calendar.DAY_OF_MONTH));
        getEditUnit(6).setCurrentVal((int)LoopManager.getInstance().getManualModalRemainTime());
    }

    /**
     * 设置时间数据
     */
    @Override
    public void saveVal() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder dateStrBuilder = new StringBuilder();
        dateStrBuilder.append(getEditUnit(3).getText()).append("-")
        .append(getEditUnit(4).getText()).append("-")
        .append(getEditUnit(5).getText()).append(PageManager.SPACE_FILL_1)
        .append(getEditUnit(0).getText()).append(":")
        .append(getEditUnit(1).getText()).append(":")
        .append(getEditUnit(2).getText());
        try {
            long time = dateFormat.parse(dateStrBuilder.toString()).getTime()-System.currentTimeMillis();
            CmdUtil.setDate(dateFormat.parse(dateStrBuilder.toString()));
            //PropertiesUtil.setPropertyOrReplaceDefault(Consts.KEY_DEVICE_MANUAL_OPERATION_TIME, );
            LoopManager loopManager = LoopManager.getInstance();
            loopManager.setManualModeLastTime(Long.parseLong(getEditUnit(6).getText()));
            if (NetworkManager.getInstance().is4G_Modal()) {
                Connection.getInstance().setLastReceiveDataDateFrom4G(time);
            } else {
                Connection.getInstance().setLastReceiveDataDateFromEnte(time);
            }
            /*if (loopManager.isManualActionModal()) {
            	loopManager.();
            }*/
        } catch (IOException | InterruptedException | ParseException e) {
            logger.error(LoggerUtil.convertException2String(e));
        }
    }
}
